# """
# Translate Api: YouDaoFanYi   (http://fanyi.youdao.com),
# """
#
# Headers = {'Accept': ' application/json, text/javascript, */*; q=0.01',
#            'Accept-Encoding': ' gzip, deflate, br',
#            'Accept-Language': ' zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
#            'Cache-Control': ' no-cache',
#            'Connection': ' keep-alive',
#            'Content-Length': ' 297',
#            'Content-Type': ' application/x-www-form-urlencoded; charset=UTF-8',
#            'Cookie': ' OUTFOX_SEARCH_USER_ID_NCOO=961122329.116641; OUTFOX_SEARCH_USER_ID="206961477@10.169.0.82"; P_INFO=null; _ntes_nnid=5359ff7dafdb52e4516c98c25745e7c4,1636606573818; UM_distinctid=17da814727ac5a-0007863e899bc3-59191459-144000-17da814727b9e3; DICT_PERS=v2|weixin-web-xue||DICT||web||2592000000||1647671025337||222.212.251.238||wxoXQUDj3iURIbpxDzOlUg2uhiuah8||lM0fPuhMUm0km0fgKO4wuRUlhHezh4qS0wBkf6FPLYl0pzh4q4n4PS06LP4Um0LlW0e40Lqz0HUY06B0HOW0L6u0; JSESSIONID=aaaid0USrNlBMcq3Xxnay; DICT_SESS=v2|DzbPzr2bwWUEnfPBnfUY0P4nLlfRHkf0YG6LO5OMgL0TKhfqz0M64R6B6MwyO4gBRTS6LOEnfgFRQSOfeK0fpy0QZOMQynfkE0; DICT_LOGIN=3||1649491779661; fanyi-ad-id=305426; fanyi-ad-closed=1; DICT_UGC=be3af0da19b5c5e6aa4e17bd8d90b28a|; JSESSIONID=abckOtgNnai46ggm2xnay; ___rl__test__cookies=1649491979805',
#            'Host': ' fanyi.youdao.com',
#            'Origin': ' https://fanyi.youdao.com',
#            'Pragma': ' no-cache',
#            'Referer': ' https://fanyi.youdao.com/',
#            'Sec-Fetch-Dest': ' empty',
#            'Sec-Fetch-Mode': ' cors',
#            'Sec-Fetch-Site': ' same-origin',
#            'User-Agent': ' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36 Edg/100.0.1185.29',
#            'X-Requested-With': ' XMLHttpRequest',
#            'sec-ch-ua': ' " Not A;Brand";v="99", "Chromium";v="100", "Microsoft Edge";v="100"',
#            'sec-ch-ua-mobile': ' ?0',
#            'sec-ch-ua-platform': '"Windows"'}
#
#
# def auto_translate(source_string):
#     api_url = 'https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
#     Post_dic = {'i': source_string,
#                 'from': 'AUTO',
#                 'to': 'AUTO',
#                 'smartresult': 'dict',
#                 'client': 'fanyideskweb',
#                 'salt': '16494919798131',
#                 'sign': 'e237c4f7565effe649998f62a8591a60',
#                 'lts': '1649491979813',
#                 'bv': 'cfddf5227f0e08de65d069a5a4aeacca',
#                 'doctype': 'json',
#                 'version': '2.1',
#                 'keyfrom': 'fanyi.web',
#                 'action': 'FY_BY_REALTlME'}
import BaseLib.util.ObjectTools.String
import random
import urllib.parse
from BaseLib.util.Net import Setting
from BaseLib.util.base.LOGGER import LOGGER

import requests


class language_codes:
    English = 'en'
    Chinese = 'zh'


def mk_sign(app_id, query, salt, password):
    byte = str(app_id) + query + str(salt) + password
    return BaseLib.util.ObjectTools.String.string_to_md5(byte)


class BaiduTranslater:
    def __init__(self, LOGGER=LOGGER(), ToLanguage=language_codes.Chinese):
        self.APP_ID = Setting.BAIDU_API_APP_ID
        self.APP_PASSWORD = 'Z8xZpgmGF0myw7qgnteq'
        self.salt = random.randint(1, 10 ** 10)
        self.ToLanguage = ToLanguage
        self.LOGGER = LOGGER

    def translate(self, query, source_language='auto'):
        self.LOGGER.info(f'translate word:{query}')
        sign = mk_sign(self.APP_ID, query, self.salt, self.APP_PASSWORD)

        POST_DATA = {'q': query,
                     'from': source_language,
                     'to': self.ToLanguage,
                     'appid': self.APP_ID,
                     'salt': self.salt,
                     'sign': sign}
        url = Setting.BAIDU_API_TRANSLATER_URL + '?' + urllib.parse.urlencode(POST_DATA)
        res = requests.get(url)
        Ret = res.json()
        self.LOGGER.debug(f'response:{str(Ret)}')
        try:
            Trans_Results = Ret['trans_result']
            for Trans_Result in Trans_Results:
                yield {'src': Trans_Result['src'], 'trans': Trans_Result['dst']}
        except:
            print(Ret)


def test(LOGGER_):
    Translater = BaiduTranslater(LOGGER_, language_codes.Chinese)
    print(next(Translater.translate('like')))


if __name__ == '__main__':
    LOGGER = _mainlib.LOGGERED.LOG.Logger(print_level=0)
    test(LOGGER)
